import base64

import json
import pickle

from django import http
from django.http import HttpResponseBadRequest
from django.http import JsonResponse
from django.shortcuts import render

from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU, GoodsCategory, GoodsVisitCount
from utils.response_code import RETCODE


class CartsView(View):
    def post(self, request):

        user_id = request.user.id
        dict = json.loads(request.body.decode())
        sku_id = dict.get('sku_id')
        count = dict.get('count')
        selected = dict.get('selected', True)
        if not all([sku_id, count]):
            return JsonResponse({'code': RETCODE.NODATAERR, 'errmag': '参数不全'})
        try:
            SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': '没有此商品'})
        try:
            count = int(count)
        except Exception:
            return HttpResponseBadRequest('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseBadRequest('参数selected有误')
        if user_id is None:
            carts_str = request.COOKIES.get('carts')
            if carts_str is None:
                carts = {}
            else:
                carts = pickle.loads(base64.b64decode(carts_str))
            if sku_id in carts:
                origin_count = carts[sku_id][count]
                count += origin_count
            carts[sku_id] = {
                'count': count,
                'selected': selected
            }
            p = pickle.dumps(carts)
            en = base64.b64encode(p)
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
            response.set_cookie('carts', en, max_age=3600)
            return response
        else:
            conn = get_redis_connection('carts')
            pl = conn.pipeline()
            pl.hincrby('user_id:%s' % user_id, sku_id, count)
            pl.sadd('user_selected:%s' % user_id, sku_id)
            pl.execute()
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})

    def get(self, request):
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('user_id:%s' % user.id)
            redis_cart_selected = redis_conn.smembers('user_selected:%s' % user.id)
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_cart_selected
                }
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart is None:
                cart_dict = {}
            else:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        sku_list = []
        for sku in skus:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'count': int(cart_dict.get(sku.id).get('count')),
                'selected': str(cart_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })
        context = {
            'cart_skus': sku_list
        }
        return render(request, 'cart.html', context)

    def put(self, request):

        user = request.user
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected')
        if not all([sku_id, count]):
            return http.JsonResponse({'code': RETCODE.ALLOWERR, 'errmsg': '请输入必须参数'})
        try:
            count = int(count)
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.ALLOWERR, 'errmag': '请输入正确的数量'})
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception:
            return http.JsonResponse({'code': RETCODE.ALLOWERR, 'errmsg': '请输入正确的商品id'})
        if not isinstance(selected, bool):
            return http.HttpResponseBadRequest('参数selected有误')
        if user.is_authenticated:
            redis_coon = get_redis_connection('carts')
            pl = redis_coon.pipeline()
            pl.hset('user_id:%s' % user.id, sku_id, count)
            pl.execute()
            if selected is True:
                pl.sadd('user_selected:%s' % user.id)
            else:
                pl.srem('user_selected:%s' % user.id)
            cart_sku = {
                'id': sku.id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'amount': count * sku.price,
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_sku': cart_sku})
        else:
            carts_str = request.COOKIES.get('carts')
            if carts_str is not None:
                carts_dict = pickle.loads(base64.b64decode(carts_str))
            else:
                carts_dict = {}
            if sku_id in carts_dict:
                carts_dict[sku_id] = {
                    'count': count,
                    'selected': selected,
                }
            carts_str = base64.b64encode(pickle.dumps(carts_dict))
            cart_sku = {
                'id': sku.id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'amount': count * sku.price,
            }
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_sku': cart_sku})
            response.set_cookie('carts', carts_str, max_age=3600)
            return response

    def delete(self, request):
        user = request.user
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        if sku_id is None:
            return http.JsonResponse({'code': RETCODE.ALLOWERR, 'errmsg': '请输入必须参数'})
        try:
            sku = SKU.objects.get(pk=sku_id)
        except Exception:
            return http.JsonResponse({'code': RETCODE.ALLOWERR, 'errmsg': '请输入正确的商品id'})
        if user.is_authenticated:
            redis_coon = get_redis_connection('carts')
            pl = redis_coon.pipeline()
            pl.hdel('user_id:%s' % user.id, sku_id)
            pl.srem('user_selected:%s' % user.id, sku_id)
            pl.execute()
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
        else:
            carts_str = request.COOKIES.get('carts')
            if carts_str is not None:
                carts_dict = pickle.loads(base64.b64decode(carts_str))
            else:
                carts_dict = {}
            if sku_id in carts_dict:
                del carts_dict[sku_id]
            carts_str = base64.b64encode(pickle.dumps(carts_dict))
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
            response.set_cookie('carts', carts_str, max_age=3600)
            return response


class CartsSelectAllView(View):
    def put(self, request):
        user = request.user
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseBadRequest('参数selected有误')
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart = redis_conn.hgetall('user_id:%s' % user.id)
            sku_id_list = cart.keys()
            if selected:
                redis_conn.sadd('user_selected:%s' % user.id, *sku_id_list)
            else:
                redis_conn.srem('user_selected:%s' % user.id, *sku_id_list)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            cart = request.COOKIES.get('carts')
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
                for sku_id in cart:
                    cart[sku_id]['selected'] = selected
                cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                response.set_cookie('carts', cookie_cart, max_age=3600)


class CartsSimpleView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            sku_id_count = redis_conn.hgetall('user_id:%s' % user.id)
            selected = redis_conn.smembers('user_selected:%s' % user.id)
            carts = []
            for sku_id in selected:
                sku = SKU.objects.get(pk=int(sku_id))
                carts.append({
                    'count': int(sku_id_count[sku_id]),
                    'name': sku.name,
                    'default_image_url': sku.default_image.url
                })
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_skus': carts})
        else:
            carts_str = request.COOKIES.get('carts')
            if carts_str is not None:
                carts_dict = pickle.loads(base64.b64decode(carts_str))
            else:
                carts_dict = {}
            carts = []
            sku_ids = carts_dict.keys()
            for sku_id in sku_ids:
                sku = SKU.objects.get(pk=sku_id)
                if carts_dict[sku_id]['selected']:
                    carts.append({
                        'count': carts_dict[sku_id]['count'],
                        'name': sku.name,
                        'default_image_url': sku.default_image.url,
                    })
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'cart_skus': carts})
